import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:test01/okhttp_test/pojo/attention_pojo.dart';
import 'package:test01/okhttp_test/util/request_http.dart';

import 'my_canvas.dart';

class MyWieghtPage extends StatefulWidget {
  const MyWieghtPage({Key key}) : super(key: key);

  @override
  _MyWieghtPageState createState() => _MyWieghtPageState();
}

class _MyWieghtPageState extends State<MyWieghtPage> {
  final SlidableController slidableController = SlidableController();

  ///定义接受数据的对象
  GetMyWigets getMyWigets = GetMyWigets();

  ///控制器
  ScrollController scrollController = ScrollController();

  ///定义获取的体重列表
  List<GetRecordLists> getRecordList = [];

  ///获取目标体重输入数据
  double targetWeightInputValue;

  ///判断是否到了最后数据
  bool isLast = false;
  //点击之后的下标
  int mm;

  //最大体重值
  double maxWeight;

  //刻度长度
  double scaleWeight;

  @override
  void initState() {
    super.initState();
    //调用接口
    getUserWeight();

    //监听滚动到底部
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        if (isLast) {
          print("==================后面没有数据拉==================");
        } else {
          //左拉加载更多
          getUserWeightRefresh();
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    ///判断最大体重以及Y轴的刻度尺
    scaleWeightNumber();
    return Scaffold(
      appBar: AppBars(),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            //体重折线图
            weightLineChart(),
            //目标体重
            targetWeightWidget(),
            Container(
              width: MediaQuery.of(context).size.width - 32,
              height: 48,
              alignment: Alignment.centerLeft,
              child: Text("体重记录"),
            ),
            //体重列表
            myWeightList(),
          ],
        ),
      ),
      //添加体重
      bottomNavigationBar: addWeightList(),
    );
  }

  ///删除体重
  deleteWeight(int i) async {
    bool result = await delWeight(
        interface: "/appuser/web/user/delWeight", id: getRecordList[i].id);
    if (result) {
      setState(() {
        getRecordList.clear();
        getUserWeight();
      });
    }
  }

  ///调用用户记录体重的接口
  getUserWeight() async {
    getMyWigets = await getWeightRecords(
        interface: "/appuser/web/user/getWeightRecords", page: 1, size: 5);

    ///复制请求的页面
    getMyWigets.page = 1;
    if (getMyWigets != null) {
      getRecordList = [];
      getMyWigets.recordList.forEach((element) {
        getRecordList.add(element);
        setState(() {});
      });
    }
  }

  ///刷新的数据
  getUserWeightRefresh() async {
    int page = getMyWigets.page + 1;
    //定义数据列表为空
    GetMyWigets newGetMyWigets = GetMyWigets();
    newGetMyWigets = await getWeightRecords(
        interface: "/appuser/web/user/getWeightRecords", page: page, size: 5);
    //调取接口值
    if (newGetMyWigets != null) {
      //数组添加数据
      newGetMyWigets.recordList.forEach((element) {
        getRecordList.add(element);
      });
      getMyWigets = newGetMyWigets;
      getMyWigets.page = page;
      print("================当前页面${getMyWigets.page}");
      isLast = false;
      setState(() {});
    } else {
      isLast = true;
      setState(() {});
    }
  }

  ///判断最大体重以及Y轴的刻度尺
  scaleWeightNumber() {
    maxWeight = 0.0;
    for (int i = 0; i < getRecordList.length; i++) {
      if (maxWeight < getRecordList[i].weight) {
        maxWeight = getRecordList[i].weight;
      }
      print(
          "=============获取的数据${getRecordList[i].weight}==============${getRecordList[i].dateTime}");
    }
    if (getMyWigets.targetWeight != null) {
      maxWeight = maxWeight > getMyWigets.targetWeight
          ? maxWeight
          : getMyWigets.targetWeight;
    }
    scaleWeight = ((((maxWeight + 20) / 100).ceil()) * 100).toDouble();
  }

  ///AppBAr
  Widget AppBars() {
    return AppBar(
      centerTitle: true,
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios, color: Colors.black),
        onPressed: () {
          ///界面返回
          Navigator.of(context).pop();
          print("返回");
        },
      ),
      backgroundColor: Colors.white,
      elevation: 1,
      title: Text(
        "我的体重",
        style: TextStyle(fontSize: 18, color: Color.fromRGBO(17, 17, 17, 1)),
      ),
    );
  }

  ///体重列表item
  Widget myWeightItem(int i) {
    return Container(
      height: 48,
      width: MediaQuery.of(context).size.width,
      child: Slidable(
        actionPane: SlidableDrawerActionPane(),
        //滑动风格
        actionExtentRatio: 0.2,
        // key: Key(i.toString()),
        controller: slidableController,
        enabled: i != i ? false : true,
        child: Container(
          height: 48,
          width: MediaQuery.of(context).size.width,
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      width: 0.5, color: Color.fromRGBO(153, 153, 153, 0.2)))),
          child: Row(
            children: <Widget>[
              Container(
                child: Text(
                  getRecordList[getRecordList.length - i - 1].dateTime,
                  style: TextStyle(
                      fontSize: 14, color: Color.fromRGBO(153, 153, 153, 1)),
                ),
              ),
              Spacer(),
              Container(
                child: Text(
                  "${getRecordList[getRecordList.length - i - 1].weight}KG",
                  style: TextStyle(
                      fontSize: 18, color: Color.fromRGBO(17, 17, 17, 1)),
                ),
              ),
            ],
          ),
        ),
        secondaryActions: <Widget>[
          GestureDetector(
            onTap: () {
              print("==========删除记录体重=============");
              deleteWeight(i);
            },
            child: Container(
              width: 101,
              height: 48,
              color: Color.fromRGBO(255, 64, 89, 1),
              alignment: Alignment.center,
              child: Text(
                "删除",
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
    //体重记录列表
  }

  ///体重列表
  Widget myWeightList() {
    return Container(
      width: MediaQuery.of(context).size.width - 32,
      height: (48 * getRecordList.length).toDouble(),
      child: ListView.builder(
        physics: NeverScrollableScrollPhysics(),
        reverse: true,
        itemBuilder: (BuildContext context, int i) {
          return GestureDetector(
            onTap: () {
              print("===================单击了$i=====================");
            },
            child: myWeightItem(i),
          );
        },
        itemCount: getRecordList.length,
      ),
    );
  }

  ///目标体重输入提示框
  Future<dynamic> targetWeightInput() {
    return showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          child: Container(
            width: 260,
            height: 168,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5),
            ),
            child: Center(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 20),
                  child: Text(
                    "请输入目标体重",
                    style: TextStyle(
                        fontSize: 18, color: Color.fromRGBO(17, 17, 17, 1)),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      width: 140,
                      height: 44,
                      child: TextField(
                        textAlign: TextAlign.center,

                        ///设置只能输入数字
                        inputFormatters: [
                          LengthLimitingTextInputFormatter(6),
                        ],
                        keyboardType: TextInputType.number,
                        cursorColor: Color.fromRGBO(153, 153, 153, 1),
                        decoration: InputDecoration(
                          ///获取焦点
                          focusedBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                            color: Colors.grey.withOpacity(0.2),
                          )),

                          ///默认状态下
                          enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                            color: Colors.grey.withOpacity(0.2),
                          )),
                        ),
                        onChanged: (value) {
                          targetWeightInputValue = double.parse(value);
                          setState(() {});
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 4),
                      child: Text(
                        "KG",
                        style: TextStyle(
                            fontSize: 16,
                            color: Color.fromRGBO(153, 153, 153, 1)),
                      ),
                    ),
                  ],
                ),
                Spacer(),
                Container(
                  height: 50,
                  margin: EdgeInsets.only(top: 20.5),
                  child: Row(
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                        },
                        child: Container(
                            alignment: Alignment.center,
                            width: 140,
                            height: 50,
                            decoration: BoxDecoration(
                                border: Border(
                              top: BorderSide(
                                  width: 0.5,
                                  color: Color.fromRGBO(204, 204, 204, 0.8)),
                              right: BorderSide(
                                  width: 0.5,
                                  color: Color.fromRGBO(204, 204, 204, 0.8)),
                            )),
                            child: Text(
                              "取消",
                              style: TextStyle(
                                  fontSize: 18,
                                  color: Color.fromRGBO(0, 0, 0, 1)),
                            )),
                      ),
                      GestureDetector(
                        onTap: () async {
                          bool sult;
                          if (targetWeightInputValue < 999 &&
                              targetWeightInputValue > 0) {
                            sult = await saveTargetWeights(
                                targetWeight: targetWeightInputValue,
                                interface:
                                    "/appuser/web/user/saveTargetWeight");
                            if (sult) {
                              Fluttertoast.showToast(
                                  msg: "记录成功！",
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.BOTTOM,
                                  textColor: Colors.white,
                                  fontSize: 14.0);
                              getUserWeight();
                              setState(() {});
                              Navigator.pop(context);
                            } else {
                              Fluttertoast.showToast(
                                  msg: "请输入正确的信息！",
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.BOTTOM,
                                  textColor: Colors.white,
                                  fontSize: 14.0);
                            }
                          } else {
                            Fluttertoast.showToast(
                                msg: "请输入正确的信息！",
                                toastLength: Toast.LENGTH_SHORT,
                                gravity: ToastGravity.BOTTOM,
                                textColor: Colors.white,
                                fontSize: 14.0);
                          }
                        },
                        child: Container(
                            alignment: Alignment.center,
                            height: 50,
                            width: 140,
                            decoration: BoxDecoration(
                                border: Border(
                              top: BorderSide(
                                  width: 0.5,
                                  color: Color.fromRGBO(204, 204, 204, 0.8)),
                            )),
                            child: Text(
                              "保存",
                              style: TextStyle(
                                  fontSize: 18,
                                  color: Color.fromRGBO(255, 64, 89, 1)),
                            )),
                      ),
                    ],
                  ),
                ),
              ],
            )),
          ),
        );
      },
    );
  }

  ///记录体重输入框
  Future<dynamic> WeightInput() {
    return showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          child: Container(
            width: 260,
            height: 168,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(5),
            ),
            child: Center(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 20),
                  child: Text(
                    "请输入当前体重",
                    style: TextStyle(
                        fontSize: 18, color: Color.fromRGBO(17, 17, 17, 1)),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      width: 140,
                      height: 44,
                      child: TextField(
                        textAlign: TextAlign.center,

                        ///设置只能输入数字
                        inputFormatters: [
                          LengthLimitingTextInputFormatter(6),
                        ],
                        keyboardType: TextInputType.number,
                        cursorColor: Color.fromRGBO(153, 153, 153, 1),
                        decoration: InputDecoration(
                          ///获取焦点
                          focusedBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                            color: Colors.grey.withOpacity(0.2),
                          )),

                          ///默认状态下
                          enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                            color: Colors.grey.withOpacity(0.2),
                          )),
                        ),
                        onChanged: (value) {
                          targetWeightInputValue = double.parse(value);
                          setState(() {});
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 4),
                      child: Text(
                        "KG",
                        style: TextStyle(
                            fontSize: 16,
                            color: Color.fromRGBO(153, 153, 153, 1)),
                      ),
                    ),
                  ],
                ),
                Spacer(),
                Container(
                  height: 50,
                  margin: EdgeInsets.only(top: 20.5),
                  child: Row(
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                        },
                        child: Container(
                            alignment: Alignment.center,
                            width: 140,
                            height: 50,
                            decoration: BoxDecoration(
                                border: Border(
                              top: BorderSide(
                                  width: 0.5,
                                  color: Color.fromRGBO(204, 204, 204, 0.8)),
                              right: BorderSide(
                                  width: 0.5,
                                  color: Color.fromRGBO(204, 204, 204, 0.8)),
                            )),
                            child: Text(
                              "取消",
                              style: TextStyle(
                                  fontSize: 18,
                                  color: Color.fromRGBO(0, 0, 0, 1)),
                            )),
                      ),
                      GestureDetector(
                        onTap: () async {
                          bool sult;
                          if (targetWeightInputValue < 999 &&
                              targetWeightInputValue > 0) {
                            sult = await saveWeight(
                                weight: targetWeightInputValue,
                                interface: "/appuser/web/user/saveWeight");
                            if (sult) {
                              Fluttertoast.showToast(
                                  msg: "记录成功！",
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.BOTTOM,
                                  textColor: Colors.white,
                                  fontSize: 14.0);
                              getUserWeight();
                              setState(() {});
                              Navigator.pop(context);
                            } else {
                              Fluttertoast.showToast(
                                  msg: "请输入正确的信息！",
                                  toastLength: Toast.LENGTH_SHORT,
                                  gravity: ToastGravity.BOTTOM,
                                  textColor: Colors.white,
                                  fontSize: 14.0);
                            }
                          } else {
                            Fluttertoast.showToast(
                                msg: "请输入正确的信息！",
                                toastLength: Toast.LENGTH_SHORT,
                                gravity: ToastGravity.BOTTOM,
                                textColor: Colors.white,
                                fontSize: 14.0);
                          }
                        },
                        child: Container(
                            alignment: Alignment.center,
                            height: 50,
                            width: 140,
                            decoration: BoxDecoration(
                                border: Border(
                              top: BorderSide(
                                  width: 0.5,
                                  color: Color.fromRGBO(204, 204, 204, 0.8)),
                            )),
                            child: Text(
                              "保存",
                              style: TextStyle(
                                  fontSize: 18,
                                  color: Color.fromRGBO(255, 64, 89, 1)),
                            )),
                      ),
                    ],
                  ),
                ),
              ],
            )),
          ),
        );
      },
    );
  }



  ///单击画布的布局
  Widget MyChangeWidget() {
    print("-------------------调用了刷新数据--------------------$mm");
    return mm != null
        ? Container(
            child: CustomPaint(
              // size：当child为null时，代表默认绘制区域大小，如果有child则忽略此参数，画布尺寸则为child尺寸
              size: Size(
                  (((MediaQuery.of(context).size.width - 53.5 - 21) / 5) *
                      (getRecordList.length >= 5 ? getRecordList.length : 5)),
                  300),
              painter: MyChangeY(getRecordList, context, mm, scaleWeight),
            ),
          )
        : Container();
  }

  ///点击的范围
  Widget clickRange(int i) {
    return Stack(
      children: <Widget>[
        Container(
          width: ((MediaQuery.of(context).size.width - 50 - 18) / 5),
          // 下边框
          decoration: BoxDecoration(
            color:
                Colors.primaries[i % Colors.primaries.length].withOpacity(0.0),
          ),
          height: 300,
          // margin: EdgeInsets.only(left: 1),
        ),
        i == mm
            ? Container(
                width: 50,
                height: 20,
                alignment: Alignment.center,
                margin: EdgeInsets.only(
                    top: (224 -
                                (((((224 / 5) * 5) - (224 / 5)) / scaleWeight) *
                                    (getRecordList[i].weight)) >
                            224
                        ? 224 -
                            (((((224 / 5) * 5) - (224 / 5)) / scaleWeight) *
                                (getRecordList[i].weight)) +
                            12
                        : 224 -
                            (((((224 / 5) * 5) - (224 / 5)) / scaleWeight) *
                                (getRecordList[i].weight)) -
                            32),
                    left: i == (getRecordList.length - 1) ? 10 : 0),
                decoration: BoxDecoration(
                  border: Border.all(width: 0.5, color: Colors.red),
                  color: Colors.white,
                ),
                child: Text(
                  "${getRecordList[i].weight}kg",
                  style: TextStyle(fontSize: 12),
                ),
              )
            : Container()
      ],
    );
  }

  ///体重折线图
  Widget weightLineChart() {
    return Container(
      height: 300,
      width: MediaQuery.of(context).size.width,
      child: Stack(
        children: <Widget>[
          ///X轴
          Container(
            margin: EdgeInsets.only(
              left: 53.5 - 16,
            ),
            // color: Colors.white,
            child: CustomPaint(
              // size：当child为null时，代表默认绘制区域大小，如果有child则忽略此参数，画布尺寸则为child尺寸
              size: Size(MediaQuery.of(context).size.width - 32 - 21, 224),
              painter: MyPainterX(
                  getRecordList, scaleWeight, getMyWigets.targetWeight),
            ),
          ),

          ///X轴以及轴的点
          Container(
            width: MediaQuery.of(context).size.width - 53.5 - 21 - 21,
            margin: EdgeInsets.only(
              left: 53.5 + 21,
            ),
            height: 268,
            alignment: Alignment.center,
            child: SingleChildScrollView(
                controller: scrollController,
                scrollDirection: Axis.horizontal,
                reverse: true,
                child: Container(
                  width: ((MediaQuery.of(context).size.width - 53.5 - 21) / 5) *
                      (getRecordList.length >= 5 ? getRecordList.length : 5),
                  height: 268,
                  child: Stack(
                    children: <Widget>[
                      ///X轴画布
                      Container(
                        child: CustomPaint(
                          // size：当child为null时，代表默认绘制区域大小，如果有child则忽略此参数，画布尺寸则为child尺寸
                          size: Size(
                              (((MediaQuery.of(context).size.width -
                                          53.5 -
                                          21) /
                                      5) *
                                  (getRecordList.length >= 5
                                      ? getRecordList.length
                                      : 5)),
                              300),
                          painter: MyPainterY(
                              getRecordList, context, mm, scaleWeight),
                        ),
                      ),

                      MyChangeWidget(),

                      ///X轴点击事件
                      Container(
                        height: 226,
                        child: ListView.builder(
                          physics: NeverScrollableScrollPhysics(),
                          scrollDirection: Axis.horizontal,
                          reverse: true,
                          itemBuilder: (BuildContext context, int i) {
                            return GestureDetector(
                              onTap: () {
                                print(
                                    "===================单击了$i=====================");
                                mm = i;
                                setState(() {});
                              },
                              child: clickRange(i),
                            );
                          },
                          itemCount: getRecordList.length,
                        ),
                      ),
                    ],
                  ),
                )),
          ),
        ],
      ),
    );
  }

  ///目标体重
  Widget targetWeightWidget() {
    return GestureDetector(
      onTap: () {
        targetWeightInput();
      },
      child: Container(
        height: 48,
        width: MediaQuery.of(context).size.width - 32,
        child: Row(
          children: <Widget>[
            Text(
              "目标体重",
              style:
                  TextStyle(fontSize: 16, color: Color.fromRGBO(17, 17, 17, 1)),
            ),
            Container(
              alignment: Alignment.centerRight,
              width: MediaQuery.of(context).size.width - 95 - 46,
              margin: EdgeInsets.only(left: 15),
              child: getMyWigets.targetWeight != null
                  ? Text(
                      "${getMyWigets.targetWeight}KG",
                      style: TextStyle(
                          fontSize: 16,
                          color: Color.fromRGBO(153, 153, 153, 1)),
                    )
                  : Text(""),
            ),
            Spacer(),
            Container(
              margin: EdgeInsets.only(left: 12),
              child: Icon(
                Icons.arrow_forward_ios_sharp,
                size: 18,
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///添加体重列表
  Widget addWeightList() {
    return GestureDetector(
      onTap: () {
        WeightInput();
      },
      child: Container(
        height: 49,
        width: MediaQuery.of(context).size.width,
        alignment: Alignment.center,
        color: Color.fromRGBO(51, 51, 51, 1),
        child: Text(
          "记录体重",
          style: TextStyle(fontSize: 16, color: Colors.white),
        ),
      ),
    );
  }
}
